using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml;
using UnityEngine;
using UI.BankingPanel.Data;

/// <summary>
/// 真正的Excel导出器
/// 生成标准的Excel .xlsx文件格式
/// 不依赖第三方库，使用OpenXML标准
/// </summary>
public static class TrueExcelExporter
{
    /// <summary>
    /// 导出押注数据到真正的Excel文件
    /// </summary>
    /// <param name="bankingData">银行数据</param>
    /// <param name="fileName">文件名（不含扩展名）</param>
    /// <returns>导出结果信息</returns>
    public static ExportResult ExportBankingDataToExcel(BankingData bankingData, string fileName = null)
    {
        try
        {
            if (bankingData == null)
            {
                return new ExportResult(false, "数据为空，无法导出");
            }

            // 生成文件名
            if (string.IsNullOrEmpty(fileName))
            {
                fileName = $"押注数据_{DateTime.Now:yyyyMMdd_HHmmss}";
            }

            // 获取导出路径
            string filePath = GetExportPath(fileName + ".xlsx");
            
            // 生成Excel文件
            CreateExcelFile(bankingData, filePath);
            
            Debug.Log($"[TrueExcelExporter] Excel文件导出成功: {filePath}");
            
            return new ExportResult(true, $"Excel导出成功！\n文件路径: {filePath}", filePath);
        }
        catch (Exception ex)
        {
            Debug.LogError($"[TrueExcelExporter] Excel导出失败: {ex.Message}\n{ex.StackTrace}");
            return new ExportResult(false, $"Excel导出失败: {ex.Message}");
        }
    }

    /// <summary>
    /// 创建Excel文件
    /// </summary>
    /// <param name="bankingData">银行数据</param>
    /// <param name="filePath">文件路径</param>
    private static void CreateExcelFile(BankingData bankingData, string filePath)
    {
        // 创建临时目录
        string tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
        Directory.CreateDirectory(tempDir);

        try
        {
            // 创建Excel文件结构
            CreateExcelStructure(tempDir, bankingData);
            
            // 压缩为xlsx文件
            CompressToXlsx(tempDir, filePath);
        }
        finally
        {
            // 清理临时目录
            if (Directory.Exists(tempDir))
            {
                Directory.Delete(tempDir, true);
            }
        }
    }

    /// <summary>
    /// 创建Excel文件结构
    /// </summary>
    /// <param name="tempDir">临时目录</param>
    /// <param name="bankingData">银行数据</param>
    private static void CreateExcelStructure(string tempDir, BankingData bankingData)
    {
        // 创建必要的目录结构
        Directory.CreateDirectory(Path.Combine(tempDir, "_rels"));
        Directory.CreateDirectory(Path.Combine(tempDir, "docProps"));
        Directory.CreateDirectory(Path.Combine(tempDir, "xl"));
        Directory.CreateDirectory(Path.Combine(tempDir, "xl", "_rels"));
        Directory.CreateDirectory(Path.Combine(tempDir, "xl", "worksheets"));

        // 创建各种XML文件
        CreateContentTypes(tempDir);
        CreateRels(tempDir);
        CreateApp(tempDir);
        CreateCore(tempDir);
        CreateWorkbook(tempDir);
        CreateWorkbookRels(tempDir);
        CreateWorksheet(tempDir, bankingData);
        CreateSharedStrings(tempDir, bankingData);
        CreateStyles(tempDir);
    }

    /// <summary>
    /// 创建[Content_Types].xml
    /// </summary>
    private static void CreateContentTypes(string tempDir)
    {
        string content = @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?>
<Types xmlns=""http://schemas.openxmlformats.org/package/2006/content-types"">
    <Default Extension=""rels"" ContentType=""application/vnd.openxmlformats-package.relationships+xml""/>
    <Default Extension=""xml"" ContentType=""application/xml""/>
    <Override PartName=""/xl/workbook.xml"" ContentType=""application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml""/>
    <Override PartName=""/xl/worksheets/sheet1.xml"" ContentType=""application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml""/>
    <Override PartName=""/xl/sharedStrings.xml"" ContentType=""application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml""/>
    <Override PartName=""/xl/styles.xml"" ContentType=""application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml""/>
    <Override PartName=""/docProps/core.xml"" ContentType=""application/vnd.openxmlformats-package.core-properties+xml""/>
    <Override PartName=""/docProps/app.xml"" ContentType=""application/vnd.openxmlformats-officedocument.extended-properties+xml""/>
</Types>";
        
        File.WriteAllText(Path.Combine(tempDir, "[Content_Types].xml"), content, Encoding.UTF8);
    }

    /// <summary>
    /// 创建_rels/.rels
    /// </summary>
    private static void CreateRels(string tempDir)
    {
        string content = @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?>
<Relationships xmlns=""http://schemas.openxmlformats.org/package/2006/relationships"">
    <Relationship Id=""rId1"" Type=""http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument"" Target=""xl/workbook.xml""/>
    <Relationship Id=""rId2"" Type=""http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties"" Target=""docProps/core.xml""/>
    <Relationship Id=""rId3"" Type=""http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties"" Target=""docProps/app.xml""/>
</Relationships>";
        
        File.WriteAllText(Path.Combine(tempDir, "_rels", ".rels"), content, Encoding.UTF8);
    }

    /// <summary>
    /// 创建docProps/app.xml
    /// </summary>
    private static void CreateApp(string tempDir)
    {
        string content = @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?>
<Properties xmlns=""http://schemas.openxmlformats.org/officeDocument/2006/extended-properties"" xmlns:vt=""http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes"">
    <Application>Unity坐庄收款系统</Application>
    <DocSecurity>0</DocSecurity>
    <ScaleCrop>false</ScaleCrop>
    <SharedDoc>false</SharedDoc>
    <HyperlinksChanged>false</HyperlinksChanged>
    <AppVersion>1.0</AppVersion>
</Properties>";
        
        File.WriteAllText(Path.Combine(tempDir, "docProps", "app.xml"), content, Encoding.UTF8);
    }

    /// <summary>
    /// 创建docProps/core.xml
    /// </summary>
    private static void CreateCore(string tempDir)
    {
        string now = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ssZ");
        string content = $@"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?>
<cp:coreProperties xmlns:cp=""http://schemas.openxmlformats.org/package/2006/metadata/core-properties"" xmlns:dc=""http://purl.org/dc/elements/1.1/"" xmlns:dcterms=""http://purl.org/dc/terms/"" xmlns:dcmitype=""http://purl.org/dc/dcmitype/"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"">
    <dc:title>押注数据报表</dc:title>
    <dc:creator>Unity坐庄收款系统</dc:creator>
    <dcterms:created xsi:type=""dcterms:W3CDTF"">{now}</dcterms:created>
    <dcterms:modified xsi:type=""dcterms:W3CDTF"">{now}</dcterms:modified>
</cp:coreProperties>";
        
        File.WriteAllText(Path.Combine(tempDir, "docProps", "core.xml"), content, Encoding.UTF8);
    }

    /// <summary>
    /// 创建xl/workbook.xml
    /// </summary>
    private static void CreateWorkbook(string tempDir)
    {
        string content = @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?>
<workbook xmlns=""http://schemas.openxmlformats.org/spreadsheetml/2006/main"" xmlns:r=""http://schemas.openxmlformats.org/officeDocument/2006/relationships"">
    <sheets>
        <sheet name=""押注数据"" sheetId=""1"" r:id=""rId1""/>
    </sheets>
</workbook>";
        
        File.WriteAllText(Path.Combine(tempDir, "xl", "workbook.xml"), content, Encoding.UTF8);
    }

    /// <summary>
    /// 创建xl/_rels/workbook.xml.rels
    /// </summary>
    private static void CreateWorkbookRels(string tempDir)
    {
        string content = @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?>
<Relationships xmlns=""http://schemas.openxmlformats.org/package/2006/relationships"">
    <Relationship Id=""rId1"" Type=""http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet"" Target=""worksheets/sheet1.xml""/>
    <Relationship Id=""rId2"" Type=""http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings"" Target=""sharedStrings.xml""/>
    <Relationship Id=""rId3"" Type=""http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles"" Target=""styles.xml""/>
</Relationships>";
        
        File.WriteAllText(Path.Combine(tempDir, "xl", "_rels", "workbook.xml.rels"), content, Encoding.UTF8);
    }

    /// <summary>
    /// 创建工作表数据
    /// </summary>
    private static void CreateWorksheet(string tempDir, BankingData bankingData)
    {
        var sb = new StringBuilder();
        sb.AppendLine(@"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?>");
        sb.AppendLine(@"<worksheet xmlns=""http://schemas.openxmlformats.org/spreadsheetml/2006/main"" xmlns:r=""http://schemas.openxmlformats.org/officeDocument/2006/relationships"">");
        sb.AppendLine(@"<sheetData>");

        int rowIndex = 1;
        
        // 标题行
        sb.AppendLine($@"<row r=""{rowIndex}"">");
        sb.AppendLine(@"<c r=""A1"" t=""inlineStr""><is><t>押注数据导出报表</t></is></c>");
        sb.AppendLine(@"</row>");
        rowIndex++;

        // 导出时间
        sb.AppendLine($@"<row r=""{rowIndex}"">");
        sb.AppendLine($@"<c r=""A{rowIndex}"" t=""inlineStr""><is><t>导出时间: {DateTime.Now:yyyy-MM-dd HH:mm:ss}</t></is></c>");
        sb.AppendLine(@"</row>");
        rowIndex++;

        // 赔率
        sb.AppendLine($@"<row r=""{rowIndex}"">");
        sb.AppendLine($@"<c r=""A{rowIndex}"" t=""inlineStr""><is><t>赔率: {bankingData.odds}</t></is></c>");
        sb.AppendLine(@"</row>");
        rowIndex += 2;

        // 数据汇总
        var stats = bankingData.GetStatisticsData();
        sb.AppendLine($@"<row r=""{rowIndex}"">");
        sb.AppendLine($@"<c r=""A{rowIndex}"" t=""inlineStr""><is><t>=== 数据汇总 ===</t></is></c>");
        sb.AppendLine(@"</row>");
        rowIndex++;

        sb.AppendLine($@"<row r=""{rowIndex}"">");
        sb.AppendLine($@"<c r=""A{rowIndex}"" t=""inlineStr""><is><t>项目</t></is></c>");
        sb.AppendLine($@"<c r=""B{rowIndex}"" t=""inlineStr""><is><t>金额</t></is></c>");
        sb.AppendLine(@"</row>");
        rowIndex++;

        sb.AppendLine($@"<row r=""{rowIndex}"">");
        sb.AppendLine($@"<c r=""A{rowIndex}"" t=""inlineStr""><is><t>总数据</t></is></c>");
        sb.AppendLine($@"<c r=""B{rowIndex}""><v>{stats.revenueTotal}</v></c>");
        sb.AppendLine(@"</row>");
        rowIndex++;

        sb.AppendLine($@"<row r=""{rowIndex}"">");
        sb.AppendLine($@"<c r=""A{rowIndex}"" t=""inlineStr""><is><t>自己吃码</t></is></c>");
        sb.AppendLine($@"<c r=""B{rowIndex}""><v>{stats.eatCodeTotal}</v></c>");
        sb.AppendLine(@"</row>");
        rowIndex++;

        sb.AppendLine($@"<row r=""{rowIndex}"">");
        sb.AppendLine($@"<c r=""A{rowIndex}"" t=""inlineStr""><is><t>上报数据</t></is></c>");
        sb.AppendLine($@"<c r=""B{rowIndex}""><v>{stats.reportTotal}</v></c>");
        sb.AppendLine(@"</row>");
        rowIndex += 2;

        // 分类统计 - 总数据
        sb.AppendLine($@"<row r=""{rowIndex}"">");
        sb.AppendLine($@"<c r=""A{rowIndex}"" t=""inlineStr""><is><t>=== 总数据 ===</t></is></c>");
        sb.AppendLine(@"</row>");
        rowIndex++;

        sb.AppendLine($@"<row r=""{rowIndex}"">");
        sb.AppendLine($@"<c r=""A{rowIndex}"" t=""inlineStr""><is><t>号码</t></is></c>");
        sb.AppendLine($@"<c r=""B{rowIndex}"" t=""inlineStr""><is><t>押注金额</t></is></c>");
        sb.AppendLine(@"</row>");
        rowIndex++;

        var totalDataNumbers = GetNumbersWithData(bankingData.GetAllNumberBetData(), DataType.Total);
        foreach (var item in totalDataNumbers)
        {
            sb.AppendLine($@"<row r=""{rowIndex}"">");
            sb.AppendLine($@"<c r=""A{rowIndex}"" t=""inlineStr""><is><t>{item.Key:D2}</t></is></c>");
            sb.AppendLine($@"<c r=""B{rowIndex}""><v>{item.Value}</v></c>");
            sb.AppendLine(@"</row>");
            rowIndex++;
        }
        rowIndex++;

        // 分类统计 - 自己吃码
        sb.AppendLine($@"<row r=""{rowIndex}"">");
        sb.AppendLine($@"<c r=""A{rowIndex}"" t=""inlineStr""><is><t>=== 自己吃码 ===</t></is></c>");
        sb.AppendLine(@"</row>");
        rowIndex++;

        sb.AppendLine($@"<row r=""{rowIndex}"">");
        sb.AppendLine($@"<c r=""A{rowIndex}"" t=""inlineStr""><is><t>号码</t></is></c>");
        sb.AppendLine($@"<c r=""B{rowIndex}"" t=""inlineStr""><is><t>吃码金额</t></is></c>");
        sb.AppendLine(@"</row>");
        rowIndex++;

        var eatCodeNumbers = GetNumbersWithData(bankingData.GetAllNumberBetData(), DataType.EatCode);
        foreach (var item in eatCodeNumbers)
        {
            sb.AppendLine($@"<row r=""{rowIndex}"">");
            sb.AppendLine($@"<c r=""A{rowIndex}"" t=""inlineStr""><is><t>{item.Key:D2}</t></is></c>");
            sb.AppendLine($@"<c r=""B{rowIndex}""><v>{item.Value}</v></c>");
            sb.AppendLine(@"</row>");
            rowIndex++;
        }
        rowIndex++;

        // 分类统计 - 上报数据
        sb.AppendLine($@"<row r=""{rowIndex}"">");
        sb.AppendLine($@"<c r=""A{rowIndex}"" t=""inlineStr""><is><t>=== 上报数据 ===</t></is></c>");
        sb.AppendLine(@"</row>");
        rowIndex++;

        sb.AppendLine($@"<row r=""{rowIndex}"">");
        sb.AppendLine($@"<c r=""A{rowIndex}"" t=""inlineStr""><is><t>号码</t></is></c>");
        sb.AppendLine($@"<c r=""B{rowIndex}"" t=""inlineStr""><is><t>上报金额</t></is></c>");
        sb.AppendLine(@"</row>");
        rowIndex++;

        var reportNumbers = GetNumbersWithData(bankingData.GetAllNumberBetData(), DataType.Report);
        foreach (var item in reportNumbers)
        {
            sb.AppendLine($@"<row r=""{rowIndex}"">");
            sb.AppendLine($@"<c r=""A{rowIndex}"" t=""inlineStr""><is><t>{item.Key:D2}</t></is></c>");
            sb.AppendLine($@"<c r=""B{rowIndex}""><v>{item.Value}</v></c>");
            sb.AppendLine(@"</row>");
            rowIndex++;
        }

        sb.AppendLine(@"</sheetData>");
        sb.AppendLine(@"</worksheet>");

        File.WriteAllText(Path.Combine(tempDir, "xl", "worksheets", "sheet1.xml"), sb.ToString(), Encoding.UTF8);
    }

    /// <summary>
    /// 创建共享字符串
    /// </summary>
    private static void CreateSharedStrings(string tempDir, BankingData bankingData)
    {
        string content = @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?>
<sst xmlns=""http://schemas.openxmlformats.org/spreadsheetml/2006/main"" count=""0"" uniqueCount=""0"">
</sst>";
        
        File.WriteAllText(Path.Combine(tempDir, "xl", "sharedStrings.xml"), content, Encoding.UTF8);
    }

    /// <summary>
    /// 创建样式
    /// </summary>
    private static void CreateStyles(string tempDir)
    {
        string content = @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?>
<styleSheet xmlns=""http://schemas.openxmlformats.org/spreadsheetml/2006/main"">
    <numFmts count=""0""/>
    <fonts count=""1"">
        <font>
            <sz val=""11""/>
            <name val=""Calibri""/>
        </font>
    </fonts>
    <fills count=""2"">
        <fill>
            <patternFill patternType=""none""/>
        </fill>
        <fill>
            <patternFill patternType=""gray125""/>
        </fill>
    </fills>
    <borders count=""1"">
        <border>
            <left/>
            <right/>
            <top/>
            <bottom/>
            <diagonal/>
        </border>
    </borders>
    <cellStyleXfs count=""1"">
        <xf numFmtId=""0"" fontId=""0"" fillId=""0"" borderId=""0""/>
    </cellStyleXfs>
    <cellXfs count=""1"">
        <xf numFmtId=""0"" fontId=""0"" fillId=""0"" borderId=""0"" xfId=""0""/>
    </cellXfs>
</styleSheet>";
        
        File.WriteAllText(Path.Combine(tempDir, "xl", "styles.xml"), content, Encoding.UTF8);
    }

    /// <summary>
    /// 压缩为xlsx文件
    /// </summary>
    private static void CompressToXlsx(string tempDir, string outputPath)
    {
        // 使用Unity内置的压缩功能或者手动创建ZIP
        // 这里使用简单的方法：调用系统的压缩功能
        
        #if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN
            // Windows平台使用PowerShell压缩
            var startInfo = new System.Diagnostics.ProcessStartInfo
            {
                FileName = "powershell.exe",
                Arguments = $"-Command \"Compress-Archive -Path '{tempDir}\\*' -DestinationPath '{outputPath}' -Force\"",
                UseShellExecute = false,
                CreateNoWindow = true
            };
            
            using (var process = System.Diagnostics.Process.Start(startInfo))
            {
                process.WaitForExit();
            }
        #else
            // 其他平台使用手动ZIP创建
            CreateZipManually(tempDir, outputPath);
        #endif
    }

    /// <summary>
    /// 手动创建ZIP文件（适用于非Windows平台）
    /// </summary>
    private static void CreateZipManually(string sourceDir, string outputPath)
    {
        // 简化版本：直接复制文件结构（用于测试）
        // 在实际项目中，您可能需要使用第三方ZIP库
        Debug.LogWarning("当前平台不支持自动压缩，请手动将临时文件夹压缩为.xlsx文件");
        
        // 作为备选方案，我们创建一个包含所有文件的目录
        string backupDir = outputPath.Replace(".xlsx", "_backup");
        if (Directory.Exists(backupDir))
        {
            Directory.Delete(backupDir, true);
        }
        
        CopyDirectory(sourceDir, backupDir);
        Debug.Log($"Excel文件结构已保存到: {backupDir}");
    }

    /// <summary>
    /// 复制目录
    /// </summary>
    private static void CopyDirectory(string sourceDir, string destDir)
    {
        Directory.CreateDirectory(destDir);
        
        foreach (string file in Directory.GetFiles(sourceDir))
        {
            string destFile = Path.Combine(destDir, Path.GetFileName(file));
            File.Copy(file, destFile, true);
        }
        
        foreach (string dir in Directory.GetDirectories(sourceDir))
        {
            string destSubDir = Path.Combine(destDir, Path.GetFileName(dir));
            CopyDirectory(dir, destSubDir);
        }
    }

    /// <summary>
    /// 获取有数据的号码列表
    /// </summary>
    private static Dictionary<int, float> GetNumbersWithData(List<NumberBetData> allData, DataType dataType)
    {
        var result = new Dictionary<int, float>();
        
        foreach (var betData in allData)
        {
            float value = 0;
            switch (dataType)
            {
                case DataType.Total:
                    value = betData.totalBetAmount;
                    break;
                case DataType.EatCode:
                    value = betData.selfBetAmount;
                    break;
                case DataType.Report:
                    value = betData.reportAmount;
                    break;
            }
            
            if (value > 0)
            {
                result[betData.number] = value;
            }
        }
        
        return result;
    }

    /// <summary>
    /// 获取导出文件路径
    /// </summary>
    private static string GetExportPath(string fileName)
    {
        string exportDir;
        
        #if UNITY_ANDROID && !UNITY_EDITOR
            exportDir = Path.Combine(Application.persistentDataPath, "Exports");
        #else
            exportDir = Path.Combine(Application.persistentDataPath, "Exports");
        #endif
        
        if (!Directory.Exists(exportDir))
        {
            Directory.CreateDirectory(exportDir);
        }
        
        return Path.Combine(exportDir, fileName);
    }

    /// <summary>
    /// 数据类型枚举
    /// </summary>
    private enum DataType
    {
        Total,      // 总数据
        EatCode,    // 吃码
        Report      // 上报
    }
} 